import React, { PureComponent, Fragment, useState, useEffect } from 'react';
import { Form, Select, Input, Checkbox, Card, Radio } from 'antd';
import { Editor } from '@tinymce/tinymce-react'
import auth from '@/utils/auth';

const createInput = ({ list = [], disabled = false }) => {
    return <Input disabled={disabled}></Input>
}
const createSelect = ({ list = [], disabled = false }) => {
    return <Select placeholder={'请选择'} disabled={disabled}>
        {
            list.map((item) => (
                <Select.Option lable={item.name} key={item.value} value={item.value}>
                    {item.name}
                </Select.Option>
            ))
        }
    </Select>
}
const createCheckbox = ({ list = [] }) => {
    return <Checkbox.Group>
        {
            list.map((item) => {
                return <Checkbox value={item.value} key={item.value}>{item.name}</Checkbox>
            })
        }
    </Checkbox.Group>
}
const createRadio = ({ list = [] }) => {
    return <Radio.Group>
        {
            list.map((item) => {
                return <Radio value={item.value} key={item.value}>{item.name}</Radio>
            })
        }
    </Radio.Group>
}
const getContext = (selector) => {
    const config = {
        input: createInput,
        select: createSelect,
        checkbox: createCheckbox,
        radio: createRadio
    }
    return config[selector];
}
class HandleCreate {
    context = null
    constructor(selector) {
        this.context = getContext(selector);
    }
    createNode(buildParams) {
        let list = buildParams.optionList && buildParams.optionList.list;
        if (buildParams.nameFiled || buildParams.valueFiled) {
            if (buildParams.nameFiled && buildParams.valueFiled) {
                console.log('nameFiled和valueFiled必须配对使用');
            }
            list = list.map((item) => {
                return {
                    name: item[buildParams.nameFiled],
                    value: item[buildParams.valueFiled]
                }
            })
        }
        buildParams.list = list;
        return this.context(buildParams);
    }
}
// 缓存实例化
class CreateFactory {
    examples = {};
    getExample(selector) {
        let oExample = this.examples[selector];
        if (oExample === undefined) {
            oExample = this.examples[selector] = new HandleCreate(selector)
        }
        return oExample;
    }
}
const formItemLayout = {
    labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
    },
    wrapperCol: {
        xs: { span: 16 },
        sm: { span: 16 },
    },
    labelAlign: 'left',
};
const MyEditor = (context, content, onChange, getFieldDecorator) => (
    <Form.Item key="tinyEditor" label={context.label} {...formItemLayout}>
        {getFieldDecorator(`${context.name}`, {
            initialValue: content,
        })(
            <Input style={{ display: 'none' }} />
        )}
        <Editor
            inline={false}
            selector='editorStateRef'
            apiKey='choaz6h7ymg6y289qn90hxy99esmes9xl2on2xn3e88o2lic'
            ref='tinyEditor'
            value={content}
            onEditorChange={(e) => {
                onChange(e, context)
            }}
            init={{
                height: '100px',
                plugins: `link`,
                toolbar: `formatselect | bold italic strikethrough forecolor backcolor
alignleft aligncenter alignright alignjustify
numlist bullist outdent indent`,
            }} />
    </Form.Item>

);
@Form.create({})
class FormModal extends PureComponent {
    // static getDerivedStateFromProps(props, state) {
    //     if (!state.freshData && props.defaultData) {
    //         const res = {};
    //         props.defaultData.forEach((item) => {
    //             if (item.type === 'editor') {
    //                 res[item.name] = item.initialValue;
    //             }
    //         })
    //         return { ...state, freshData: res };
    //     }
    //     return null;
    // }

    constructor(props) {
        super(props)
        this.state = {
            freshData: this.getFreshData(props.defaultData)
        }
    }
    componentWillReceiveProps(nextProps, prevProps) {
        if (nextProps.defaultData && !this.state.freshData.initialSign) {
            this.state = {
                freshData: { ...this.getFreshData(nextProps.defaultData), initialSign: 1 }
            }
        }
    }
    getFreshData(data) {
        if (!Array.isArray(data)) return {};
        const res = {};
        data.forEach((item) => {
            if (item.type === 'editor') {
                res[item.name] = item.initialValue;
            }
        })
        return res;
    }
    handleEditorChange(e, context) {
        const { freshData } = this.state;
        this.setState({
            freshData: { ...freshData, [`${context.name}`]: e }
        })
    }
    render() {
        const { form, defaultData } = this.props;
        const { freshData } = this.state;
        const { getFieldDecorator } = form;
        const createFactory = new CreateFactory();
        return <Form size="small">
            {
                defaultData.map((item) => {
                    if (item.type === 'editor') {
                        return MyEditor(item, freshData[item.name], this.handleEditorChange.bind(this), getFieldDecorator); //<MyEditor label={item.label} key={item.name} content={editorContent} onChange={this.handleEditorChange} />
                    } else {
                        return <Form.Item label={item.label} {...formItemLayout} key={item.name} hidden={item.hidden}>
                            {getFieldDecorator(`${item.name}`, {
                                initialValue: typeof item.initialValue === 'number' ? String(item.initialValue) : item.initialValue,
                            })(
                                createFactory.getExample(item.type).createNode(item)
                            )}
                        </Form.Item>
                    }
                })
            }

        </Form >
    }
}

export default FormModal;